package tsm.main;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Vector;

import tsm.constant.ClientConstant;
import tsm.constant.Language;
import tsm.constant.MagicConstant;
import tsm.model.RadioButtonGroup;
import tsm.network.BeUSession;
import tsm.network.NetworkCore;
import tsm.network.SerializeHelper;
import tsm.widget.Link;
import tsm.widget.MagicPage;
import tsm.widget.renderer.MagicRenderer;
import tsm.widget.renderer.MagicRendererV2;

import com.core.tsm.Button;
import com.core.tsm.ButtonGroup;
import com.core.tsm.CheckBox;
import com.core.tsm.ComboBox;
import com.core.tsm.Command;
import com.core.tsm.Component;
import com.core.tsm.Font;
import com.core.tsm.Image;
import com.core.tsm.Label;
import com.core.tsm.List;
import com.core.tsm.RadioButton;
import com.core.tsm.TextArea;
import com.core.tsm.TextField;
import com.core.tsm.events.ActionEvent;
import com.core.tsm.events.ActionListener;
import com.core.tsm.plaf.Border;
import com.core.tsm.plaf.Style;

public class MagicExecutor {

	public synchronized static void deCompilePage(ByteArrayInputStream buffer, boolean showNow) {
		try {
			MagicPage page = null;
			do {
				int byteCode = SerializeHelper.readInt(buffer);
				//				System.out.println("byteCode " + byteCode);
				switch (byteCode) {
				case MagicConstant.CREATE_PAGE: {
					byte scrollable = SerializeHelper.readByte(buffer);
					byte layout = SerializeHelper.readByte(buffer);
					byte row = SerializeHelper.readByte(buffer);
					byte column = SerializeHelper.readByte(buffer);
					String pageTitle = SerializeHelper.readString(buffer);
					int bgColor = SerializeHelper.readInt(buffer);
					byte scrollVisible = SerializeHelper.readByte(buffer);
					int pageId = SerializeHelper.readInt(buffer);
					Core.getInstance().closeDialog();
					page = new MagicPage(scrollable, pageId, pageTitle, layout, row, column, bgColor, scrollVisible, Core.getInstance(), -1);
					int previousPageId = Core.getInstance().addPage(page);
					//					System.out.println("############CREATE PAGE: " + pageId + " previousPageId " + previousPageId);
					if (previousPageId > 0) {
						page.setPreviousPageId(previousPageId);
					}
					System.gc();
					break;
				}
				case MagicConstant.ADD_CONTAINER_TO_PAGE: {
					byte constraints = SerializeHelper.readByte(buffer);
					boolean containerScrollable = SerializeHelper.readBoolean(buffer);
					byte containerLayout = SerializeHelper.readByte(buffer);
					byte containerRow = SerializeHelper.readByte(buffer);
					byte containerColumn = SerializeHelper.readByte(buffer);
					byte topPadding = SerializeHelper.readByte(buffer);
					byte leftPadding = SerializeHelper.readByte(buffer);
					byte bottomPadding = SerializeHelper.readByte(buffer);
					byte rightPadding = SerializeHelper.readByte(buffer);
					byte topMargin = SerializeHelper.readByte(buffer);
					byte leftMargin = SerializeHelper.readByte(buffer);
					byte bottomMargin = SerializeHelper.readByte(buffer);
					byte rightMargin = SerializeHelper.readByte(buffer);
					int containerId = SerializeHelper.readInt(buffer);
					page.addContainer(constraints, containerScrollable, containerLayout, containerRow, containerColumn, containerId, -1, topPadding, leftPadding, bottomPadding,
							rightPadding, topMargin, leftMargin, bottomMargin, rightMargin);
					break;
				}
				case MagicConstant.ADD_CONTAINER_TO_CONTAINER: {
					int parentsId = SerializeHelper.readInt(buffer);
					byte constraints = SerializeHelper.readByte(buffer);
					boolean containerScrollable = SerializeHelper.readBoolean(buffer);
					byte containerLayout = SerializeHelper.readByte(buffer);
					byte containerRow = SerializeHelper.readByte(buffer);
					byte containerColumn = SerializeHelper.readByte(buffer);
					int containerId = SerializeHelper.readInt(buffer);
					page.addContainer(constraints, containerScrollable, containerLayout, containerRow, containerColumn, containerId, parentsId, (byte) -1, (byte) -1, (byte) -1,
							(byte) -1, (byte) -1, (byte) -1, (byte) -1, (byte) -1);
					break;
				}
				case MagicConstant.ADD_COMPONENT_LABEL: { // sticker?
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						byte textPos = SerializeHelper.readByte(buffer);
						byte align = SerializeHelper.readByte(buffer);
						byte[] image = SerializeHelper.readBytes(buffer);
						byte borderStyle = SerializeHelper.readByte(buffer);
						String labelName = SerializeHelper.readString(buffer);
						int color = SerializeHelper.readInt(buffer);
						byte startTicker = SerializeHelper.readByte(buffer);
						boolean isFocusable = SerializeHelper.readBoolean(buffer);
						int bgColor = SerializeHelper.readInt(buffer);
						byte topPadding = SerializeHelper.readByte(buffer);
						byte leftPadding = SerializeHelper.readByte(buffer);
						byte bottomPadding = SerializeHelper.readByte(buffer);
						byte rightPadding = SerializeHelper.readByte(buffer);
						byte topMargin = SerializeHelper.readByte(buffer);
						byte leftMargin = SerializeHelper.readByte(buffer);
						byte bottomMargin = SerializeHelper.readByte(buffer);
						byte rightMargin = SerializeHelper.readByte(buffer);
						int componentId = SerializeHelper.readInt(buffer);
						Label label = new Label(labelName);
						label.setFocusable(isFocusable);
						if (borderStyle == 1) {
							Border border = Border.createRidgeBorder(5, 0xffffff);
							label.getSelectedStyle().setBorder(border);
							label.getUnselectedStyle().setBorder(border);
						}
						if (color != -1) {
							label.getSelectedStyle().setFgColor(color);
							label.getUnselectedStyle().setFgColor(color);
						}
						if (bgColor != -1) {
							label.getSelectedStyle().setBgTransparency(255);
							label.getUnselectedStyle().setBgTransparency(255);
							label.getSelectedStyle().setBgColor(bgColor);
							label.getUnselectedStyle().setBgColor(bgColor);
						}
						if (topPadding != -1) {
							label.getUnselectedStyle().setPadding(Button.TOP, topPadding);
							label.getSelectedStyle().setPadding(Button.TOP, topPadding);
							label.getPressedStyle().setPadding(Button.TOP, topPadding);
						}
						if (leftPadding != -1) {
							label.getUnselectedStyle().setPadding(Button.LEFT, leftPadding);
							label.getSelectedStyle().setPadding(Button.LEFT, leftPadding);
							label.getPressedStyle().setPadding(Button.LEFT, leftPadding);
						}
						if (bottomPadding != -1) {
							label.getUnselectedStyle().setPadding(Button.BOTTOM, bottomPadding);
							label.getSelectedStyle().setPadding(Button.BOTTOM, bottomPadding);
							label.getPressedStyle().setPadding(Button.BOTTOM, bottomPadding);
						}
						if (rightPadding != -1) {
							label.getUnselectedStyle().setPadding(Button.RIGHT, rightPadding);
							label.getSelectedStyle().setPadding(Button.RIGHT, rightPadding);
							label.getPressedStyle().setPadding(Button.RIGHT, rightPadding);
						}
						if (topMargin != -1) {
							label.getUnselectedStyle().setMargin(Button.TOP, topMargin);
							label.getSelectedStyle().setMargin(Button.TOP, topMargin);
							label.getPressedStyle().setMargin(Button.TOP, topMargin);
						}
						if (leftMargin != -1) {
							label.getUnselectedStyle().setMargin(Button.LEFT, leftMargin);
							label.getSelectedStyle().setMargin(Button.LEFT, leftMargin);
							label.getPressedStyle().setMargin(Button.LEFT, leftMargin);
						}
						if (bottomMargin != -1) {
							label.getUnselectedStyle().setMargin(Button.BOTTOM, bottomMargin);
							label.getSelectedStyle().setMargin(Button.BOTTOM, bottomMargin);
							label.getPressedStyle().setMargin(Button.BOTTOM, bottomMargin);
						}
						if (rightMargin != -1) {
							label.getUnselectedStyle().setMargin(Button.RIGHT, rightMargin);
							label.getSelectedStyle().setMargin(Button.RIGHT, rightMargin);
							label.getPressedStyle().setMargin(Button.RIGHT, rightMargin);
						}
						label.setTextPosition(textPos);
						label.getSelectedStyle().setAlignment(align);
						label.getUnselectedStyle().setAlignment(align);
						if (startTicker != 0) {
							label.startTicker();
						}
						if (image != null && image.length > 0) {
							// try {
							// label.setIcon(Image.createImage("/av4.png"));
							// } catch (IOException e) {
							// e.printStackTrace();
							// }
							if (image.length == 4) {
								page.addComponentImageId(NetworkCore.bytes2Int(image), componentId);
							} else {
								label.setIcon(Image.createImage(image, 0, image.length));
							}
						}
						label.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						page.addMagicComponent(label, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_BUTTON: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						byte textPos = SerializeHelper.readByte(buffer);
						byte align = SerializeHelper.readByte(buffer);
						byte[] image = SerializeHelper.readBytes(buffer);
						byte bigIcon = SerializeHelper.readByte(buffer);
						byte[] selectedImage = SerializeHelper.readBytes(buffer);
						byte backgroundStyle = SerializeHelper.readByte(buffer);
						byte style = SerializeHelper.readByte(buffer);
						String buttonName = SerializeHelper.readString(buffer);
						int color = SerializeHelper.readInt(buffer);
						byte font = SerializeHelper.readByte(buffer);
						byte fontSize = SerializeHelper.readByte(buffer);
						byte fontStyle = SerializeHelper.readByte(buffer);
						boolean isFocusable = SerializeHelper.readBoolean(buffer);
						byte topPadding = SerializeHelper.readByte(buffer);
						byte leftPadding = SerializeHelper.readByte(buffer);
						byte bottomPadding = SerializeHelper.readByte(buffer);
						byte rightPadding = SerializeHelper.readByte(buffer);
						byte topMargin = SerializeHelper.readByte(buffer);
						byte leftMargin = SerializeHelper.readByte(buffer);
						byte bottomMargin = SerializeHelper.readByte(buffer);
						byte rightMargin = SerializeHelper.readByte(buffer);
						final byte[] actionByte = SerializeHelper.readBytes(buffer);
						int componentId = SerializeHelper.readInt(buffer);
						Button button = new Button(buttonName);
						if (style == 2) { //bevel
							Border border = Border.createBevelLowered(0x373737, 0xa3a3a3, 0xffffff, 0xffffff);
							Style unselected = new Style();
							unselected.setBgColor(0xffffff);
							unselected.setBgImage(null);
							unselected.setBorder(border);
							Style selected = new Style();
							selected.setBgColor(0xd9d9d9);
							selected.setBgImage(null);
							selected.setBorder(border);
							button.setSelectedStyle(selected);
							button.setUnselectedStyle(unselected);
							button.setPressedStyle(selected);
						}
						if (backgroundStyle != -1) {
							button.getUnselectedStyle().setBackgroundType(backgroundStyle);
							button.getSelectedStyle().setBackgroundType(backgroundStyle);
							button.getPressedStyle().setBackgroundType(backgroundStyle);
						}
						button.setTextPosition(textPos);
						if (color != -1) {
							button.getSelectedStyle().setFgColor(color);
							button.getUnselectedStyle().setFgColor(color);
							button.getPressedStyle().setFgColor(color);
						}
						if (font != -1) {
							Font f = Font.createSystemFont(font, fontStyle, fontSize);
							button.getSelectedStyle().setFont(f);
							button.getUnselectedStyle().setFont(f);
							button.getPressedStyle().setFont(f);
						}
						button.setAlignment(align);
						// button.getStyle().setAlignment(align);
						if (image != null && image.length > 0) {
							// button.getStyle().setBorder(Border.createLineBorder(1));
							// button.getStyle().setBgImage(null);
							// button.getStyle().setBgColor(0);
							button.setIcon(Image.createImage(image, 0, image.length));
							if (bigIcon == 1) {
								button.getUnselectedStyle().setBgImage(null);
								button.getSelectedStyle().setBgImage(null);
								button.getPressedStyle().setBgImage(null);
								button.getUnselectedStyle().setBgTransparency(0);
								button.getSelectedStyle().setBgTransparency(0);
								button.getPressedStyle().setBgTransparency(0);
							} else if (bigIcon == 2) {
								if (selectedImage != null && selectedImage.length > 0) {
									Style selected = new Style();
									selected.setBgImage(Image.createImage(selectedImage, 0, selectedImage.length));
									button.setSelectedStyle(selected);
									button.getUnselectedStyle().setBgImage(null);
									button.getPressedStyle().setBgImage(null);
									button.getUnselectedStyle().setBgTransparency(0);
									button.getPressedStyle().setBgTransparency(0);
									Border border = Border.createEmpty();
									button.getPressedStyle().setBorder(border);
								}
							}
						}
						button.setFocusable(isFocusable);
						if (topPadding != -1) {
							button.getUnselectedStyle().setPadding(Button.TOP, topPadding);
							button.getSelectedStyle().setPadding(Button.TOP, topPadding);
							button.getPressedStyle().setPadding(Button.TOP, topPadding);
						}
						if (leftPadding != -1) {
							button.getUnselectedStyle().setPadding(Button.LEFT, leftPadding);
							button.getSelectedStyle().setPadding(Button.LEFT, leftPadding);
							button.getPressedStyle().setPadding(Button.LEFT, leftPadding);
						}
						if (bottomPadding != -1) {
							button.getUnselectedStyle().setPadding(Button.BOTTOM, bottomPadding);
							button.getSelectedStyle().setPadding(Button.BOTTOM, bottomPadding);
							button.getPressedStyle().setPadding(Button.BOTTOM, bottomPadding);
						}
						if (rightPadding != -1) {
							button.getUnselectedStyle().setPadding(Button.RIGHT, rightPadding);
							button.getSelectedStyle().setPadding(Button.RIGHT, rightPadding);
							button.getPressedStyle().setPadding(Button.RIGHT, rightPadding);
						}
						if (topMargin != -1) {
							button.getUnselectedStyle().setMargin(Button.TOP, topMargin);
							button.getSelectedStyle().setMargin(Button.TOP, topMargin);
							button.getPressedStyle().setMargin(Button.TOP, topMargin);
						}
						if (leftMargin != -1) {
							button.getUnselectedStyle().setMargin(Button.LEFT, leftMargin);
							button.getSelectedStyle().setMargin(Button.LEFT, leftMargin);
							button.getPressedStyle().setMargin(Button.LEFT, leftMargin);
						}
						if (bottomMargin != -1) {
							button.getUnselectedStyle().setMargin(Button.BOTTOM, bottomMargin);
							button.getSelectedStyle().setMargin(Button.BOTTOM, bottomMargin);
							button.getPressedStyle().setMargin(Button.BOTTOM, bottomMargin);
						}
						if (rightMargin != -1) {
							button.getUnselectedStyle().setMargin(Button.RIGHT, rightMargin);
							button.getSelectedStyle().setMargin(Button.RIGHT, rightMargin);
							button.getPressedStyle().setMargin(Button.RIGHT, rightMargin);
						}
						if (actionByte != null) {
							button.addActionListener(new ActionListener() {
								public void actionPerformed(ActionEvent evt) {
									deCompilePage(new ByteArrayInputStream(actionByte), true); // ?
								}
							});
						}
						button.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						page.addMagicComponent(button, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_LINK: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						String linkName = SerializeHelper.readString(buffer);
						int color = SerializeHelper.readInt(buffer);
						final byte[] actionByte = SerializeHelper.readBytes(buffer);
						int componentId = SerializeHelper.readInt(buffer);
						Link link = new Link(linkName);
						if (color != -1) {
							link.getStyle().setFgColor(color);
						}
						link.getStyle().setTextDecoration(Style.TEXT_DECORATION_UNDERLINE);
						link.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								deCompilePage(new ByteArrayInputStream(actionByte), true); // ?
							}
						});
						link.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						page.addMagicComponent(link, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_CHECKBOX: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						byte textPos = SerializeHelper.readByte(buffer);
						byte align = SerializeHelper.readByte(buffer);
						String name = SerializeHelper.readString(buffer);
						int color = SerializeHelper.readInt(buffer);
						byte isChosen = SerializeHelper.readByte(buffer);
						int componentId = SerializeHelper.readInt(buffer);
						CheckBox checkBox = new CheckBox(name);
						if (color != -1) {
							checkBox.getStyle().setFgColor(color);
						}
						if (isChosen == 1) {
							checkBox.setSelected(true);
						}
						checkBox.setTextPosition(textPos);
						checkBox.getStyle().setAlignment(align);
						checkBox.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						page.addMagicComponent(checkBox, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_RADIO_BUTTON_GROUP: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						byte textPos = SerializeHelper.readByte(buffer);
						byte align = SerializeHelper.readByte(buffer);
						int color = SerializeHelper.readInt(buffer);
						int selected = SerializeHelper.readInt(buffer);
						int n = SerializeHelper.readInt(buffer);
						ButtonGroup buttonGroup = new ButtonGroup();
						for (int i = 0; i < n; i++) {
							String text = SerializeHelper.readString(buffer);
							final RadioButton radioButton = new RadioButton(text);
							radioButton.getSelectedStyle().setFgColor(color);
							radioButton.getUnselectedStyle().setFgColor(color);
							radioButton.setTextPosition(textPos);
							radioButton.getSelectedStyle().setAlignment(align);
							radioButton.getUnselectedStyle().setAlignment(align);
							buttonGroup.add(radioButton);
							page.addMagicComponent(radioButton, constraints, containerId);
						}
						buttonGroup.setSelected(selected);
						int componentId = SerializeHelper.readInt(buffer);
						RadioButtonGroup radioButtonGroup = new RadioButtonGroup(componentId, buttonGroup);
						page.addButtonGroup(radioButtonGroup);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_COMBOBOX: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						int color = SerializeHelper.readInt(buffer);
						int selected = SerializeHelper.readInt(buffer);
						int n = SerializeHelper.readInt(buffer);
						String[] dataModel = new String[n];
						for (int i = 0; i < n; i++) {
							dataModel[i] = SerializeHelper.readString(buffer);
						}
						int componentId = SerializeHelper.readInt(buffer);
						ComboBox comboBox = new ComboBox(dataModel);
						if (color != -1) {
							comboBox.getStyle().setFgColor(color);
						}
						comboBox.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						comboBox.setSelectedIndex(selected);
						page.addMagicComponent(comboBox, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_LIST: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						byte typeOfRenderer = SerializeHelper.readByte(buffer);
						int color = SerializeHelper.readInt(buffer);
						int n = SerializeHelper.readInt(buffer);
						String[] dataModel1 = new String[n];
						for (int i = 0; i < n; i++) {
							dataModel1[i] = SerializeHelper.readString(buffer);
						}
						String[] dataModel2 = null;
						int p = SerializeHelper.readInt(buffer);
						if (p > 0) {
							dataModel2 = new String[p];
							for (int i = 0; i < p; i++) {
								dataModel2[i] = SerializeHelper.readString(buffer);
							}
						}
						Image[] images = null;
						int m = SerializeHelper.readInt(buffer);
						if (m == 1) {
							images = new Image[n];
							byte[] data = SerializeHelper.readBytes(buffer);
							Image image = Image.createImage(data, 0, data.length);
							for (int i = 0; i < n; i++) {
								if (data != null) {
									images[i] = image;
								}
							}
						} else if (m > 0) {
							images = new Image[m];
							for (int i = 0; i < m; i++) {
								byte[] data = SerializeHelper.readBytes(buffer);
								if (data != null) {
									images[i] = Image.createImage(data, 0, data.length);
								}
							}
						}
						int constants = SerializeHelper.readInt(buffer);
						long[] data = null;
						if (constants > 0) {
							data = new long[constants];
							for (int i = 0; i < constants; i++) {
								data[i] = SerializeHelper.readLong(buffer);
							}
							page.setConstantsList(data);
						}
						final byte[] actionByte = SerializeHelper.readBytes(buffer);
						int componentId = SerializeHelper.readInt(buffer);

						List list = null;
						if (typeOfRenderer == 1) {
							list = new List(dataModel1);
							MagicRenderer magicRenderer = new MagicRenderer(0x138ef6, 0xd2d4d3, images);
							// list.getStyle().setBgTransparency(0);
							// list.setPaintFocusBehindList(true);
							list.setRenderer(magicRenderer);
							list.setItemGap(1);
						} else if (typeOfRenderer == 2) {
							list = new List(dataModel1);
							MagicRendererV2 r = new MagicRendererV2();
							r.setImages(images);
							//							r.setItems(dataModel1);
							r.setSubItems(dataModel2);
							list.setRenderer(r);
							list.getUnselectedStyle().setBgColor(0);
							list.getSelectedStyle().setBgColor(0);
							list.setItemGap(1);
							list.setScrollVisible(false);
						}
						if (list != null) {
							list.getSelectedStyle().setPadding(0, 0, 0, 0);
							list.getSelectedStyle().setMargin(0, 0, 0, 0);
							list.getUnselectedStyle().setPadding(0, 0, 0, 0);
							list.getUnselectedStyle().setMargin(0, 0, 0, 0);
							if (color != -1) {
								list.getSelectedStyle().setBgColor(color);
								list.getUnselectedStyle().setBgColor(color);
							}
							list.addActionListener(new ActionListener() {
								public void actionPerformed(ActionEvent evt) {
									deCompilePage(new ByteArrayInputStream(actionByte), true); // ?
								}
							});
							list.setSmoothScrolling(true);
							list.setScrollAnimationSpeed(30);
							list.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
							page.addMagicComponent(list, constraints, containerId);
						}
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_TEXTFIELD: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						String text = SerializeHelper.readString(buffer);
						int color = SerializeHelper.readInt(buffer);
						int typeOfInput = SerializeHelper.readInt(buffer);
						byte inputMode = SerializeHelper.readByte(buffer);
						int maxSize = SerializeHelper.readInt(buffer);
						boolean isEditable = SerializeHelper.readBoolean(buffer);
						boolean isFocusable = SerializeHelper.readBoolean(buffer);
						int componentId = SerializeHelper.readInt(buffer);
						TextField textField = new TextField();
						Border border = Border.createRoundBorder(4, 4, 0x33b7f8, true);
						textField.getUnselectedStyle().setBorder(border);
						border = Border.createRoundBorder(4, 4, 0xf4be78, true);
						textField.getSelectedStyle().setBorder(border);
						if (color != -1) {
							textField.getSelectedStyle().setFgColor(color);
							textField.getUnselectedStyle().setFgColor(color);
							textField.getDisabledStyle().setFgColor(color);
							textField.getPressedStyle().setFgColor(color);
						}
						int index = text.indexOf("$:");
						if (index != -1) {
							String key = text.substring(index);
							Core.getInstance();
							byte[] data = Core.getInstance().loadRMS(key);
							text = "";
							if (data != null) {
								text = new String(data);
							}
							textField.putClientProperty(MagicConstant.COMPONENT_RMS_KEY, key);
						}
						textField.setText(text);
						textField.setConstraint(typeOfInput);
						if (inputMode == MagicConstant.INPUT_MODE_Abc) {
							textField.setInputMode("Abc");
							textField.setInputModeOrder(new String[] { "Abc" });
						} else if (inputMode == MagicConstant.INPUT_MODE_ABC) {
							textField.setInputMode("ABC");
							textField.setInputModeOrder(new String[] { "ABC" });
						} else if (inputMode == MagicConstant.INPUT_MODE_abc) {
							textField.setInputMode("abc");
							textField.setInputModeOrder(new String[] { "abc" });
						} else if (inputMode == MagicConstant.INPUT_MODE_123) {
							textField.setInputMode("123");
							textField.setInputModeOrder(new String[] { "123" });
						}
						textField.setMaxSize(maxSize);
						textField.setEditable(isEditable);
						textField.setFocusable(isFocusable);
						textField.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						page.addMagicComponent(textField, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_TEXTAREA: {
					if (page != null) {
						int containerId = SerializeHelper.readInt(buffer);
						byte constraints = SerializeHelper.readByte(buffer);
						String text = SerializeHelper.readString(buffer);
						int color = SerializeHelper.readInt(buffer);
						byte rowsGap = SerializeHelper.readByte(buffer);
						int typeOfInput = SerializeHelper.readInt(buffer);
						int maxSize = SerializeHelper.readInt(buffer);
						boolean isEditable = SerializeHelper.readBoolean(buffer);
						boolean isFocusable = SerializeHelper.readBoolean(buffer);
						int bgColor = SerializeHelper.readInt(buffer);
						byte topPadding = SerializeHelper.readByte(buffer);
						byte leftPadding = SerializeHelper.readByte(buffer);
						byte bottomPadding = SerializeHelper.readByte(buffer);
						byte rightPadding = SerializeHelper.readByte(buffer);
						byte topMargin = SerializeHelper.readByte(buffer);
						byte leftMargin = SerializeHelper.readByte(buffer);
						byte bottomMargin = SerializeHelper.readByte(buffer);
						byte rightMargin = SerializeHelper.readByte(buffer);
						int componentId = SerializeHelper.readInt(buffer);
						TextArea textArea = new TextArea(text);
						if (color != -1) {
							textArea.getSelectedStyle().setFgColor(color);
							textArea.getUnselectedStyle().setFgColor(color);
							textArea.getDisabledStyle().setFgColor(color);
							textArea.getPressedStyle().setFgColor(color);
						}
						if (bgColor != -1) {
							textArea.getSelectedStyle().setBgColor(bgColor);
							textArea.getUnselectedStyle().setBgColor(bgColor);
							textArea.getDisabledStyle().setBgColor(bgColor);
							textArea.getPressedStyle().setBgColor(bgColor);
						}
						//						if (!isEditable) {
						//							textArea.getUnselectedStyle().setPadding(0, 0, 5, 0);
						//							textArea.getUnselectedStyle().setMargin(0, 0, 5, 0);
						//							textArea.getUnselectedStyle().setBgColor(0xffffff);
						//						}
						if (topPadding != -1) {
							textArea.getUnselectedStyle().setPadding(Button.TOP, topPadding);
							textArea.getSelectedStyle().setPadding(Button.TOP, topPadding);
							textArea.getPressedStyle().setPadding(Button.TOP, topPadding);
						}
						if (leftPadding != -1) {
							textArea.getUnselectedStyle().setPadding(Button.LEFT, leftPadding);
							textArea.getSelectedStyle().setPadding(Button.LEFT, leftPadding);
							textArea.getPressedStyle().setPadding(Button.LEFT, leftPadding);
						}
						if (bottomPadding != -1) {
							textArea.getUnselectedStyle().setPadding(Button.BOTTOM, bottomPadding);
							textArea.getSelectedStyle().setPadding(Button.BOTTOM, bottomPadding);
							textArea.getPressedStyle().setPadding(Button.BOTTOM, bottomPadding);
						}
						if (rightPadding != -1) {
							textArea.getUnselectedStyle().setPadding(Button.RIGHT, rightPadding);
							textArea.getSelectedStyle().setPadding(Button.RIGHT, rightPadding);
							textArea.getPressedStyle().setPadding(Button.RIGHT, rightPadding);
						}
						if (topMargin != -1) {
							textArea.getUnselectedStyle().setMargin(Button.TOP, topMargin);
							textArea.getSelectedStyle().setMargin(Button.TOP, topMargin);
							textArea.getPressedStyle().setMargin(Button.TOP, topMargin);
						}
						if (leftMargin != -1) {
							textArea.getUnselectedStyle().setMargin(Button.LEFT, leftMargin);
							textArea.getSelectedStyle().setMargin(Button.LEFT, leftMargin);
							textArea.getPressedStyle().setMargin(Button.LEFT, leftMargin);
						}
						if (bottomMargin != -1) {
							textArea.getUnselectedStyle().setMargin(Button.BOTTOM, bottomMargin);
							textArea.getSelectedStyle().setMargin(Button.BOTTOM, bottomMargin);
							textArea.getPressedStyle().setMargin(Button.BOTTOM, bottomMargin);
						}
						if (rightMargin != -1) {
							textArea.getUnselectedStyle().setMargin(Button.RIGHT, rightMargin);
							textArea.getSelectedStyle().setMargin(Button.RIGHT, rightMargin);
							textArea.getPressedStyle().setMargin(Button.RIGHT, rightMargin);
						}
						if (rowsGap != -1) {
							textArea.setRowsGap(rowsGap);
						}
						textArea.setConstraint(typeOfInput);
						textArea.setMaxSize(maxSize);
						textArea.setEditable(isEditable);
						textArea.setFocusable(isFocusable);
						textArea.putClientProperty(MagicConstant.COMPONENT_ID_KEY, new Integer(componentId));
						page.addMagicComponent(textArea, constraints, containerId);
					}
					break;
				}
				case MagicConstant.ADD_COMPONENT_TREE:
					break;
				case MagicConstant.ADD_COMPONENT_TABLE:
					break;
				case MagicConstant.ADD_COMPONENT_MEDIA:
					break;
				case MagicConstant.ADD_COMMAND: {
					if (page != null) {
						String cmdName = SerializeHelper.readString(buffer);
						byte pos = SerializeHelper.readByte(buffer);
						byte[] image = SerializeHelper.readBytes(buffer);
						byte[] action = SerializeHelper.readBytes(buffer);
						Command command;
						if (image != null && image.length > 0) {
							Image icon = Image.createImage(image, 0, image.length);
							command = new Command(cmdName, icon, ClientConstant.MAGIC_CMD);
						} else {
							command = new Command(cmdName, ClientConstant.MAGIC_CMD);
						}
						command.putClientProperty(MagicConstant.COMPONENT_ACTION_KEY, action);
						page.addCommand(command, pos);
					}
					break;
				}
				case MagicConstant.ADD_ACTION: {
					if (page != null) {
						byte oriented = SerializeHelper.readByte(buffer);
						byte[] action = SerializeHelper.readBytes(buffer);
						if (oriented == MagicConstant.LEFT) {
							page.setActionLeft(action);
						} else if (oriented == MagicConstant.RIGHT) {
							page.setActionRight(action);
						}
					}
					break;
				}
				case MagicConstant.SEND_SMS_COMMAND: {
					//					System.out.println("Send SMS");
					String syntax = SerializeHelper.readString(buffer);
					String phone = SerializeHelper.readString(buffer);
					Core.getInstance().sendSMS(syntax, phone);
					break;
				}
				case MagicConstant.SEND_A_BEAN_COMMAND: {
					break;
				}
				case MagicConstant.UPLOAD_DATA_COMMAND: {
					ByteArrayOutputStream writeStream = new ByteArrayOutputStream();
					try {
						int uploadType = SerializeHelper.readInt(buffer);
						int pageId = SerializeHelper.readInt(buffer);
						int nParamenters = SerializeHelper.readInt(buffer);
						SerializeHelper.writeInt(uploadType, writeStream);
						if (nParamenters > 0) {
							for (int i = 0; i < nParamenters; i++) {
								byte paramType = SerializeHelper.readByte(buffer); // {Integer,String,Long}
								//								System.out.println("================= get MAGIC component: " + i + " paramType = " + paramType);
								switch (paramType) {
								case MagicConstant.LIST_PARAMETERS: {
									int componentId = SerializeHelper.readInt(buffer);
									//									System.out.println("GetPage " + pageId + " widgetId = " + componentId);
									MagicPage myPage = (MagicPage) Core.getInstance().getPageById(pageId);
									if (myPage != null) {
										List list = (List) myPage.getComponentById(componentId);
										if (list != null) {
											int selected = list.getSelectedIndex();
											if (selected != -1) {
												byte getType = SerializeHelper.readByte(buffer);
												if (getType == MagicConstant.VALUE_IS_CONSTANT) {
													long[] data = myPage.getConstantsList();
													if (data != null) {
														SerializeHelper.writeLong(data[selected], writeStream);
													}
												} else if (getType == MagicConstant.VALUE_GET_FROM_COMPONENTS) {
													//													System.out.println("Get value: List Component " + selected);
													SerializeHelper.writeInt(selected, writeStream);
												}
											} else {
												Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
												return;
											}
										}
									}
									break;
								}
								case MagicConstant.BUTTON_GROUP_PARAMETERS: {
									int componentId = SerializeHelper.readInt(buffer);
									//									System.out.println("GetPage " + pageId + " widgetId = " + componentId);
									MagicPage myPage = (MagicPage) Core.getInstance().getPageById(pageId);
									if (myPage != null) {
										RadioButtonGroup radioButtonGroup = myPage.getButtonGroup(componentId);
										if (radioButtonGroup != null) {
											int selected = radioButtonGroup.getButtonGroup().getSelectedIndex();
											if (selected != -1) {
												//												System.out.println("Get value: ButtonGroup Component " + selected);
												SerializeHelper.writeInt(selected, writeStream);
											} else {
												Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
												return;
											}
										}
									}
									break;
								}
								case MagicConstant.INTEGER_PARAMETERS: {
									byte getType = SerializeHelper.readByte(buffer); // {Constant,GetFromComponent}
									if (getType == MagicConstant.VALUE_IS_CONSTANT) {
										int value = SerializeHelper.readInt(buffer);
										SerializeHelper.writeInt(value, writeStream);
									} else if (getType == MagicConstant.VALUE_GET_FROM_COMPONENTS) {
										int componentId = SerializeHelper.readInt(buffer);
										//										System.out.println("GetPage " + pageId + " widgetId = " + componentId);
										MagicPage myPage = (MagicPage) Core.getInstance().getPageById(pageId);
										if (myPage != null) {
											Component myComp = myPage.getComponentById(componentId);
											if (myComp instanceof TextField) {
												boolean mustFill = SerializeHelper.readBoolean(buffer);
												String s = ((TextField) myComp).getText();
												if (s.equals("") && mustFill) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												int value = 0;
												try {
													value = Integer.parseInt(s);
												} catch (Exception e) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value int: TextField Component " + value);
												SerializeHelper.writeInt(value, writeStream);
											} else if (myComp instanceof TextArea) {
												boolean mustFill = SerializeHelper.readBoolean(buffer);
												String s = ((TextArea) myComp).getText();
												if (s.equals("") && mustFill) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												int value = 0;
												try {
													value = Integer.parseInt(s);
												} catch (Exception e) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value int: TextArea Component " + value);
												SerializeHelper.writeInt(value, writeStream);
											} else if (myComp instanceof ComboBox) {
												int value = ((ComboBox) myComp).getSelectedIndex();
												//												System.out.println("Get value int: ComboBox Component " + value);
												SerializeHelper.writeInt(value, writeStream);
											}
										}
									}
									break;
								}
								case MagicConstant.LONG_PARAMENTERS: {
									byte getType = SerializeHelper.readByte(buffer); // {Constant,GetFromComponent}
									if (getType == MagicConstant.VALUE_IS_CONSTANT) {
										long value = SerializeHelper.readLong(buffer);
										SerializeHelper.writeLong(value, writeStream);
									} else if (getType == MagicConstant.VALUE_GET_FROM_COMPONENTS) {
										int componentId = SerializeHelper.readInt(buffer);
										//										System.out.println("GetPage " + pageId + " widgetId = " + componentId);
										MagicPage myPage = (MagicPage) Core.getInstance().getPageById(pageId);
										if (myPage != null) {
											Component myComp = myPage.getComponentById(componentId);
											if (myComp instanceof TextField) {
												boolean mustFill = SerializeHelper.readBoolean(buffer);
												String s = ((TextField) myComp).getText();
												if (s.equals("") && mustFill) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												long value = 0;
												try {
													value = Integer.parseInt(s);
												} catch (Exception e) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value long: TextField Component " + value);
												SerializeHelper.writeLong(value, writeStream);
											} else if (myComp instanceof TextArea) {
												boolean mustFill = SerializeHelper.readBoolean(buffer);
												String s = ((TextArea) myComp).getText();
												if (s.equals("") && mustFill) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												long value = 0;
												try {
													value = Long.parseLong(s);
												} catch (Exception e) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value long: TextArea Component " + value);
												SerializeHelper.writeLong(value, writeStream);
											}
										}
									}
									break;
								}
								case MagicConstant.STRING_PARAMENTERS: {
									byte getType = SerializeHelper.readByte(buffer); // {Constant,GetFromComponent}
									if (getType == MagicConstant.VALUE_IS_CONSTANT) {
										String value = SerializeHelper.readString(buffer);
										SerializeHelper.writeString(value, writeStream);
									} else if (getType == MagicConstant.VALUE_GET_FROM_COMPONENTS) {
										int componentId = SerializeHelper.readInt(buffer);
										//										System.out.println("GetPage " + pageId + " widgetId = " + componentId);
										MagicPage myPage = (MagicPage) Core.getInstance().getPageById(pageId);
										if (myPage != null) {
											Component myComp = myPage.getComponentById(componentId);
											if (myComp instanceof TextField) {
												boolean mustFill = SerializeHelper.readBoolean(buffer);
												String s = ((TextField) myComp).getText();
												if (s.equals("") && mustFill) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value String: TextField Component " + s);
												SerializeHelper.writeString(s, writeStream);
												String value = (String) myComp.getClientProperty(MagicConstant.COMPONENT_RMS_KEY);
												if (value != null) {
													Core.getInstance().saveRMS(value, s.getBytes());
												}
											} else if (myComp instanceof TextArea) {
												boolean mustFill = SerializeHelper.readBoolean(buffer);
												String s = ((TextArea) myComp).getText();
												if (s.equals("") && mustFill) {
													myPage.setFocused(myComp);
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value String: TextArea Component " + s);
												SerializeHelper.writeString(s, writeStream);
											} else if (myComp instanceof ComboBox) {
												Object value = ((ComboBox) myComp).getSelectedItem();
												if (value == null) {
													Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.WARN_INFO[ClientConstant.LANGUAGE]);
													return;
												}
												//												System.out.println("Get value String: ComboBox Component " + value);
												SerializeHelper.writeString(value.toString(), writeStream);
											}
										}
									}
									break;
								}
								case MagicConstant.BOOLEAN_PARAMENTERS: {
									byte getType = SerializeHelper.readByte(buffer); // {Constant,GetFromComponent}
									if (getType == MagicConstant.VALUE_IS_CONSTANT) {
										boolean value = SerializeHelper.readBoolean(buffer);
										SerializeHelper.writeBoolean(value, writeStream);
									} else if (getType == MagicConstant.VALUE_GET_FROM_COMPONENTS) {
										int componentId = SerializeHelper.readInt(buffer);
										//										System.out.println("GetPage " + pageId + " widgetId = " + componentId);
										MagicPage myPage = (MagicPage) Core.getInstance().getPageById(pageId);
										if (myPage != null) {
											Component myComp = myPage.getComponentById(componentId);
											if (myComp instanceof CheckBox) {
												boolean value = ((CheckBox) myComp).isSelected();
												//												System.out.println("Get value boolean: CheckBox Component " + value);
												SerializeHelper.writeBoolean(value, writeStream);
											}
										}
									}
									break;
								}
								case MagicConstant.BYTEARRAY_PARAMETERS: {
									break;
								}
								default: {
									break;
								}
								}
							}
						}
						//						System.out.println("==================Send uploaddata " + writeStream.size());
						BeUSession.uploadData(writeStream.toByteArray());
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (writeStream != null) {
							try {
								writeStream.close();
							} catch (IOException e) {
							}
						}
					}
					break;
				}
				case MagicConstant.SHOW_DIALOG_COMMAND: {
					String title = SerializeHelper.readString(buffer);
					String msg = SerializeHelper.readString(buffer);
					Core.getInstance().showInfoDialog(title, msg);
					return;
				}
				case MagicConstant.CHAT_TO_COMMAND: {
					String username = SerializeHelper.readString(buffer);
					long userId = SerializeHelper.readLong(buffer);
					Core.getInstance().addChatPage(username, true, true);
					Core.getInstance().addOrUpdateChatListModel(username);
					return;
				}
				case MagicConstant.CLOSE_PAGE_COMMAND: {
					int pageId = SerializeHelper.readInt(buffer);
					boolean isShow = SerializeHelper.readBoolean(buffer);
					if (pageId == 0) {
						Core.getInstance().removeCurrentPage(isShow);
					} else {
						Core.getInstance().removePage(pageId, isShow);
					}
					break;
				}
				case MagicConstant.EXIT_APP_COMMAND: {
					BeU.instance.notifyDestroyed();
				}
				case MagicConstant.DISCONNECT_COMMAND: {
					NetworkCore.forceClose();
					Core.getInstance().clearAllPage();
					Core.getInstance().logOff();
					return;
				}
				case MagicConstant.END_PAGE: {
					lazyLoadImage(page.getLazyLoadImage(), page.getPageId(), page.getLabelImage());
					if (showNow) {
						page.show();
					}
					//					System.out.println("================= END_PAGE showPage " + page.getPageId());
					return;
				}
				case MagicConstant.END_COMMAND: {
					//					System.out.println("================= END_COMMAND");
					// show waiting dialog
					Core.getInstance().showWaitingDialog();
					return;
				}
				case MagicConstant.REQUEST_FOCUS_COMMAND: {
					int compId = SerializeHelper.readInt(buffer);
					page.setFocusToComponent(compId);
					break;
				}
				case MagicConstant.OPEN_BUDDYPAGE_COMMAND: {
					Core.getInstance().createBuddyPage();
					break;
				}
				case MagicConstant.OPEN_CHAT_LIST_COMMAND: {
					Core.getInstance().createChatListPage();
					break;
				}
				case MagicConstant.OPEN_CONFERENCE_LIST_COMMAND: {
					Core.getInstance().createConferenceListPage();
					break;
				}
				case MagicConstant.OPEN_CONFIRM_JOIN_CONFERENCE_COMMAND: {
					Core.getInstance().createConfirmJoinConferencePage();
					break;
				}
				case MagicConstant.OPEN_INVITE_CONFERENCE_COMMAND: {
					long conferenceId = SerializeHelper.readLong(buffer);
					boolean isStart = SerializeHelper.readBoolean(buffer);
					Core.getInstance().currentConferenceId = conferenceId;
					Core.getInstance().isStartConference = isStart;
					Core.getInstance().createBuddyInviteConferencePage();
					break;
				}
				case MagicConstant.USING_CAMERA_COMMAND: {
					CameraCanvas.getInstance().show();
					BeUSession.entityForUpload = SerializeHelper.readLong(buffer);
					BeUSession.albumIdForUpload = SerializeHelper.readLong(buffer);
					break;
				}
				case MagicConstant.BROWSING_CARD_COMMAND: {
					Core.getInstance().sendFileRequest();
					BeUSession.entityForUpload = SerializeHelper.readLong(buffer);
					BeUSession.albumIdForUpload = SerializeHelper.readLong(buffer);
					break;
				}
				case MagicConstant.OPEN_PLAYER_PAGE_COMMAND: {
					Core.getInstance().currentSongId = SerializeHelper.readInt(buffer);
					BeUSession.beginStreamingAudio(Core.getInstance().currentSongId);
					// Show playerpage;
					Core.getInstance().createPlayerPage();
					break;
				}
				case MagicConstant.START_VIBRATE_COMMAND: {
					Core.getInstance().startVibrate();
					break;
				}
				case MagicConstant.OPEN_URL_TO_BROWSER_COMMAND: {
					try {
						String url = SerializeHelper.readString(buffer);
						BeU.instance.platformRequest(url);
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				}
				default:
					return;
				}
			} while (true);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void lazyLoadImage(Vector lazyLoadImage, int pageId, Vector labelImage) {
		int n = lazyLoadImage.size();
		if (n > 0) {
			for (int i = 0; i < n; i++) {
				int imageId = ((Integer) lazyLoadImage.elementAt(i)).intValue();
				int componentId = ((Integer) labelImage.elementAt(i)).intValue();
				BeUSession.getImagePage(pageId, componentId, imageId);
			}
		}
	}
}
